import { designComponent } from "src/use/designComponent";
import { DefineComponent, markRaw, reactive, watch } from "vue";
import { AppNavigator } from "./app-navigator";

export const AppNavigatorPage = designComponent({
  setup() {
    const navigator = AppNavigator.use.inject();

    const state = reactive({
      PageComponent: null as null | DefineComponent
    });

    const utils = {
      reset: async () => {
        const route = navigator.state.route;
        if (!route) return;
        let { path } = route;
        if (!path) return;
        if (path.charAt(0) === "/") {
          path = path.slice(1);
        }
        let Component = (await import("story/pages/" + path));
        Component = Component.default ? Component.default : <div>未找到路径 {path} 组件 <br/>请检查组件默认导出或路径地址是否正确</div>;
        
        state.PageComponent = markRaw(Component);
      }
    };

    watch(() => navigator.state.route.path, utils.reset, { immediate: true });

    return {
      render: () => {
        const { PageComponent } = state;
        return PageComponent ? <PageComponent /> : null;
      }
    };
  }
});
